<?php

class LightJob_Runner_Adapter_Default implements LightJob_Runner_IAdapter
{
	public function __construct()
	{
			
	}

	public function pushLogAction($txt,$file,$level='debug')
	{
		
		$fh = @fopen($file,'a+');
		if(is_resource($fh))
		{
			$this->write($fh,$txt);
			fclose($fh);
		}
		else
		{
			throw new IOException("Unable to open file '$file' for writing a log");
		}
	}
	
	public function pushMailAction($to,$from,$subject,$body)
	{
		return mail($to,$subject,$body,"From: $from");
	}
	
	public function pushCmdAction($cmd)
	{
		`$cmd`;
		
		return true;
	}
	public function pushHttpGetAction($url,$headers=array())
	{
		return $this->pushHttpAction('get',$url,array(),$headers);
	}

	public function pushHttpPostAction($url,$params=array(),$headers=array())
	{
		return $this->pushHttpAction('post',$url,$params,$headers);
	}
	
	protected function pushHttpAction($method,$url,$params=array(),$headers=array())
	{
		$urlInfo = parse_url($url);

		$userAgent = 'LightJob';
		
        switch($urlInfo['scheme']){
        case 'http':
            // timeout is 1 second
            $fp = @stream_socket_client('tcp://'.$urlInfo['host'].(@$urlInfo['port']?":{$urlInfo['port']}":':80'), $errno, $errstr, 1);
            if (!is_resource($fp) || feof($fp)) throw new Exception("Unable to connect to '$uri': Error #$errno $errstr");
            socket_set_blocking($fp,0);
            if($method==='post'){
                // POST mode
                $this->write($fp,"POST ".$urlInfo['path'].(@$urlInfo['query']?"?{$urlInfo['query']}":"").(@$urlInfo['fragment']?"?{$urlInfo['fragment']}":"")." HTTP/1.1\r\n");
                $this->write($fp,"Host: ".$urlInfo['host']."\r\n");
                $this->write($fp,"Accept: */*\r\n");
                $this->write($fp,"Connection: close\r\n");
                $this->write($fp,"User-Agent: ".$userAgent."\r\n");
                $this->write($fp,"Content-Type: application/x-www-form-urlencoded\r\n");
                if(is_array($headers))
                {
	                foreach($headers as $h=>$v){
    	            	$this->write($fp,"$h: $v\r\n");
        	        }
                }
                $tp = '';
                if(is_array($params))
                {
	                foreach($params as $p=>$v){
    	                if(is_string($v) || is_int($v)){
        	                $tp .= '&'.$p.'='.urlencode($v);
            	        }else{
                	        $tp .= '&'.$p.'='.urlencode(json_encode($v));
                    	}
                	}
                }
                $this->write($fp,"Content-Length: ".strlen($tp)."\r\n");
                $this->write($fp,"\r\n");
                stream_set_write_buffer($fp, 0);
                $this->write($fp,$tp."\r\n");
            }else{
                // GET mode
                $this->write($fp,"GET ".$urlInfo['path'].(@$urlInfo['query']?"?{$urlInfo['query']}":"").(@$urlInfo['fragment']?"?{$urlInfo['fragment']}":"")." HTTP/1.1\r\n");
                $this->write($fp,"Host: ".$urlInfo['host']."\r\n");
                $this->write($fp,"Accept: */*\r\n");
                $this->write($fp,"Connection: close\r\n");
                $this->write($fp,"User-Agent: ".$userAgent."\r\n");
                if(is_array($headers))
                {
	                foreach($headers as $h=>$v){
    	            	$this->write($fp,"$h: $v\r\n");
        	        }
                }
                $this->write($fp,"\r\n");
            }
            break;
        default:
            stream_socket_shutdown($fp, STREAM_SHUT_RDWR);
            throw new Exception("Protocol of uri '$uri' is not supported");
        }

        return true;
	}
	
    protected function write($fp,$raw)
    {
        while(($towrite = strlen($raw))>0){
            $written = fputs($fp,$raw,1024);
            $raw = substr($raw,$written);
        };
    }
	
	/**
	 * @see LightJob_Runner_IAdapter::countActions()
	 *
	 */
	public function countActions()
	{
		return 0;
	}
	
	/**
	 * @see LightJob_Runner_IAdapter::updateActions()
	 *
	 */
	public function updateActions()
	{
		return false;
	}

}